﻿using Microsoft.AspNetCore.SignalR;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;

namespace RxxAdmin.Common.Hubs
{
    public class ChatHubb : Hub
    {
        /// <summary>
        /// 重写连接事件 添加连接用户
        /// </summary>
        /// <returns></returns>
        public override Task OnConnectedAsync()
        {
            //这里可以使用Context.User来获取连接的用户信息
            // 获取当前用户信息
            var username = Context.User.Identity.Name;
            var user = HubState.Users.SingleOrDefault(x => x.UserId == Convert.ToInt32(Context?.User.FindFirstValue("UserId")));
            if (user == null)
            {
                var newUser = new HubUser
                {
                    ConnectionID = Context?.ConnectionId ?? string.Empty,
                    UserId = Convert.ToInt32(Context.User.FindFirstValue("UserId")),//根据实际业务逻辑赋值
                    UserName = Context.User.FindFirstValue("UserName"),//根据实际业务逻辑赋值
                    OnLineTime = DateTime.Now,
                };
                HubState.Users.Add(newUser);
                Clients.All.SendAsync("ReceiveMessage",1, newUser.UserName + "已上线");
            }
            return base.OnConnectedAsync();
        }
        /// <summary>
        /// 重写断开事件 移除断开用户
        /// </summary>
        /// <param name="exception"></param>
        /// <returns></returns>
        public override Task OnDisconnectedAsync(Exception? exception)
        {
            var user = HubState.Users.SingleOrDefault(x => x.UserId == Convert.ToInt32(Context?.User.FindFirstValue("UserId")));
            if (user != null)
            {
                HubState.Users.Remove(user);
                Clients.All.SendAsync("ReceiveMessage",2, user.UserName + "已离线");
            }
            return base.OnDisconnectedAsync(exception);
        }

        public async Task SendMessage(string user, string message)
        {
            await Clients.All.SendAsync("ReceiveMessage", user + "says", message);
        }

        public async Task AddToGroup(string groupName)
        {
            await Groups.AddToGroupAsync(Context.ConnectionId, groupName);

            await Clients.Group(groupName).SendAsync("ReceiveMessage", $"{Context.ConnectionId} has joined the group", $"{groupName}.");
        }

        public Task SendMessageToGroup(string groupName, string message)
        {
            return Clients.Group(groupName).SendAsync("ReceiveMessage", $"{Context.ConnectionId}", $"{message}");
        }


        public async Task RemoveFromGroup(string groupName)
        {
            await Clients.Group(groupName).SendAsync("ReceiveMessage", $"{Context.ConnectionId} has left the group", $"{groupName}.");
            await Groups.RemoveFromGroupAsync(Context.ConnectionId, groupName);
        }

        public Task SendPrivateMessage(string user, string message)
        {
            string state = Clients.User(user).SendAsync("ReceiveMessage", user, message).Status.ToString();
            return Task.CompletedTask;
        }
    }
}
